package org.ifilm.service;

import java.util.List;

import org.ifilm.dao.ProjectDao;
import org.ifilm.model.Project;
import org.ifilm.model.ProjectComment;
import org.ifilm.model.ProjectRating;
import org.ifilm.model.User;
import org.ifilm.model.UserJobPosting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Project Service implementation
 * 
 * @author Mustafa Genc
 *
 */
@Service
@Transactional
public class ProjectServiceImpl implements ProjectService {
	@Autowired
	private ProjectDao projectDao;

	@Override
	public Project createProject(Project project) {
		return projectDao.createProject(project);
	}

	@Override
	public Project getProject(Long id) {
		return projectDao.getProject(id);
	}
	
	@Override
	public List<UserJobPosting> searchPostingsByUserType(Integer page, Integer max, List<String> userTypeName) {
		return projectDao.searchPostingsByUserType(page, max, userTypeName);
	}
	
	@Override
	public List<Project> listProjects(Integer page, Integer max) {
		return projectDao.listProjects(page, max);
	}
	@Override
	public List<Project> listUserProjects(Long userId, Integer page, Integer max) {
		return projectDao.listUserProjects(userId,page, max);
	}

	@Override
	public void rateProject(ProjectRating projectRating) {
		projectDao.createProjectRating(projectRating);
		
		Project ratedProject = projectRating.getRatedProject();
		
		Double oldTotalAvgRate = (double) (ratedProject.getAverageRate() * ratedProject.getTotalRate());
		
		ratedProject.setTotalRate(ratedProject.getTotalRate() + 1);
		
		Float newAvgRate = (float) ((oldTotalAvgRate + projectRating.getRate()) / ratedProject.getTotalRate());
		ratedProject.setAverageRate(newAvgRate);
	}

	@Override
	public ProjectRating getProjectRate(Long projectId, User rater) {
		return projectDao.getProjectRate(projectId, rater);
	}

	@Override
	public void updateRate(Project project, ProjectRating oldRating, Integer newRate) {
		Double oldTotalAvgRate = (double) (project.getAverageRate() * project.getTotalRate());
		
		Float newAvgRate = (float) ((oldTotalAvgRate - oldRating.getRate() + newRate) / project.getTotalRate());
		project.setAverageRate(newAvgRate);
		
		oldRating.setRate(newRate);
	}

	@Override
	public List<ProjectComment> getComments(Long projectId) {
		return projectDao.getComments(projectId);
	}

	@Override
	public ProjectComment createProjectComment(ProjectComment projectComment) {
		return projectDao.createProjectComment(projectComment);
	}

	@Override
	public List<UserJobPosting> searchByUserDetail(User user) {
		return projectDao.searchByUserDetail(user);
	}
	
	@Override 
	public void editProject(Project project){
		//TODO
		projectDao.editProject(project);
	}

	@Override
	public User getUserById(Long userId) {
		
		return projectDao.getUserById(userId);
	}
}